import PlayerBase from "./PlayerData";
import StorageUtil from "../../framework/utils/StorageUtil";
import { AttrName } from "./AttrName";

 
/**
 * 玩家数据管理器
 */
 
export default class PlayerMgr extends PlayerBase {
    private static _instance: PlayerMgr = null;
    public static getInstance(): PlayerMgr {
        if (this._instance == null) { 
            this._instance = new PlayerMgr();
        } 
        return this._instance;
    } 

    //训练场数据
    initRoomData(){ 
        let uid = this.getKey("roleInfo","uid");
        let obj = StorageUtil.get(`roomData${uid}`,true);
        if(Object.keys(obj).length <= 0 ){
            for (let index = 1; index <= 9; index++) {
                obj[index] = 0;
            }     
        }
        StorageUtil.set(`roomData${uid}`,obj);
        console.log("初始化成功",uid,obj)
    }

    getRoom(level:number){
        let uid = this.getKey("roleInfo","uid");
        let obj = StorageUtil.get(`roomData${uid}`,true);
        return obj[level] || 0;
    }

    setRoom(level:number,val:number){
        let uid = this.getKey("roleInfo","uid");
        let obj = StorageUtil.get(`roomData${uid}`,true);
        obj[level] = val;
        StorageUtil.set(`roomData${uid}`,obj);
        return;
    }
 
    public init(data){
        super.init(data);
        this.initRoomData()
    }
    
    public getData(){
        return super.getData();
    }

    /**
     * 同步玩家数据
     * @param data 
     */
    synchronPlayerData(data:object){
        for (var key in data) {
            this.swithInfo(key,data[key])
        } 
    }


    /**
     * 监听属性公共的属性刷新
     */
    regMonitor(name:string,info:object){
        switch (name) {
            
            default:
                break;
        }
         

    }  
    //提前缓存好属性值
    beferAttr(name:string,data:Object){ 
        switch (name) { 
            default:
                break;
        } 
    }



    swithInfo(name:string,data:Object){ 
        //同步前
        this.beferAttr(name,data);
        //crud
        if(AttrName[name]){
            this.updateCrud(name,data);  
        }else{
            this.defaultSynchronInfo(name,data);
        } 

        //同步后
        this.regMonitor(name,data);
    }
 
    
    /**
     * 获取玩家属性  支持二级key获取
     * @param moduleName  模块名
     * @param key 模块内key
     */
    getKey(moduleName:string,key:string = null){
        if (!moduleName) return null;
        let moduleData = super.getData()[moduleName];
        if (!moduleData) return null; 
        if(key){
            return moduleData[key];
        } 
        return moduleData;
    } 

    
 

 
    /**
     * 检查资源
     * @param typ   道具类型
     * @param id    道具ID 
     * @param num   数量
     * @returns 
     */
    checkResource ( typ:number, id:number, num:number ) {
        //待完善
        return 0;
    }
    

}
